package cool.taomu.toolkit.jooq.provider

import com.google.inject.Inject
import com.google.inject.name.Named
import java.util.Map
import javax.sql.DataSource
import org.jooq.DSLContext
import org.jooq.SQLDialect
import org.jooq.impl.DSL
import org.slf4j.LoggerFactory

class JooqContextProvider {
    static val LOG = LoggerFactory.getLogger(JooqContextProvider)
    val Map<String, DataSource> dataSourceMap;

    @Inject(optional=true)
    @Named("taomu.jooq.url")
    String url;

    @Inject(optional=true)
    @Named("taomu.jooq.dialect")
    String dialect

    @Inject
    new(Map<String, DataSource> dataSourceMap) {
        this.dataSourceMap = dataSourceMap;
    }

    def DSLContext use(String name) {
        LOG.info("可用数据源名:{}\n选择数据源:{}", dataSourceMap.keySet, name)
        var DataSource ds = dataSourceMap.get(name);
        if (ds === null) {
            throw new IllegalArgumentException("没有数据源: " + name);
        }
        return DSL.using(ds, SQLDialect.valueOf(dialect.toUpperCase));
    }
}
